/**
 * 批量操作菜单组件
 * 支持批量预约、清洁、维护等操作
 */

import React, { useState, useEffect } from 'react';
import { RoomStatus } from '../../../types/room';
import { RoomStatusManager } from '../utils/RoomStatusManager';
import type { Room } from '../../../types/room';

export interface BatchOperation {
  id: string;
  label: string;
  icon: string;
  targetStatus: RoomStatus;
  requiresConfirmation?: boolean;
  description?: string;
  color?: string;
}

export interface BatchOperationMenuProps {
  visible: boolean;
  selectedCount: number;
  selectedCells: {
    roomId: string;
    date: string;
    roomIndex: number;
    dateIndex: number;
  }[];
  rooms: Room[];
  onClose: () => void;
  onBatchOperation: (
    operation: BatchOperation,
    cells: {
      roomId: string;
      date: string;
      roomIndex: number;
      dateIndex: number;
    }[]
  ) => void;
}

const BatchOperationMenu: React.FC<BatchOperationMenuProps> = ({
  visible,
  selectedCount,
  selectedCells,
  rooms,
  onClose,
  onBatchOperation,
}) => {
  const [isProcessing, setIsProcessing] = useState(false);

  // 定义批量操作选项
  const batchOperations: BatchOperation[] = [
    {
      id: 'batch_book',
      label: '批量预订',
      icon: '📅',
      targetStatus: RoomStatus.BOOKED,
      requiresConfirmation: false,
      description: '将选中的房间设置为已预订状态',
      color: '#2196f3',
    },
    {
      id: 'batch_available',
      label: '批量设为可用',
      icon: '🟢',
      targetStatus: RoomStatus.AVAILABLE,
      requiresConfirmation: false,
      description: '将选中的房间恢复为可用状态',
      color: '#4caf50',
    },
    {
      id: 'batch_cleaning',
      label: '批量清洁',
      icon: '🧹',
      targetStatus: RoomStatus.CLEANING,
      requiresConfirmation: false,
      description: '将选中的房间设置为清洁中状态',
      color: '#8d6e63',
    },
    {
      id: 'batch_maintenance',
      label: '批量维护',
      icon: '🔧',
      targetStatus: RoomStatus.MAINTENANCE,
      requiresConfirmation: false,
      description: '将选中的房间设置为维护中状态',
      color: '#f44336',
    },
    {
      id: 'batch_checkout',
      label: '批量退房',
      icon: '🚪',
      targetStatus: RoomStatus.CHECKED_OUT,
      requiresConfirmation: false,
      description: '将选中的房间设置为已退房状态',
      color: '#666',
    },
    {
      id: 'batch_cleaned',
      label: '批量清洁完成',
      icon: '✨',
      targetStatus: RoomStatus.CLEANED,
      requiresConfirmation: false,
      description: '将选中的房间标记为清洁完成',
      color: '#4caf50',
    },
  ];

  // ESC键关闭菜单
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    if (visible) {
      document.addEventListener('keydown', handleKeyDown);
      return () => document.removeEventListener('keydown', handleKeyDown);
    }
  }, [visible, onClose]);

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.batch-operation-menu')) {
        onClose();
      }
    };

    if (visible) {
      document.addEventListener('mousedown', handleClickOutside);
      return () =>
        document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [visible, onClose]);

  const handleOperationClick = async (operation: BatchOperation) => {
    if (isProcessing) return;

    // 直接执行操作，无需确认
    console.log(`🎯 执行批量操作: ${operation.label}`, {
      操作: operation.label,
      影响单元格: selectedCount,
      目标状态: operation.targetStatus,
    });

    setIsProcessing(true);

    try {
      // 执行批量操作
      await onBatchOperation(operation, selectedCells);

      console.log(`✅ 批量操作完成: ${operation.label}`, {
        操作: operation.label,
        影响单元格: selectedCount,
        目标状态: operation.targetStatus,
      });

      // 操作成功后关闭菜单
      onClose();
    } catch (error) {
      console.error('批量操作失败:', error);
      console.error(`批量操作失败详情: ${error}`);
    } finally {
      setIsProcessing(false);
    }
  };

  // 获取选中房间的统计信息
  const getSelectionStats = () => {
    const roomCounts = new Map<string, number>();
    const dateCounts = new Map<string, number>();

    selectedCells.forEach(cell => {
      const room = rooms.find(r => r.id === cell.roomId);
      if (room) {
        const roomKey = `${room.building}-${room.roomNumber}`;
        roomCounts.set(roomKey, (roomCounts.get(roomKey) || 0) + 1);
        dateCounts.set(cell.date, (dateCounts.get(cell.date) || 0) + 1);
      }
    });

    return {
      uniqueRooms: roomCounts.size,
      uniqueDates: dateCounts.size,
      roomCounts,
      dateCounts,
    };
  };

  if (!visible) return null;

  const stats = getSelectionStats();

  return (
    <div
      className='batch-operation-menu'
      style={{
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: 'white',
        border: '1px solid #ddd',
        borderRadius: '12px',
        boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
        zIndex: 2000,
        minWidth: '400px',
        maxWidth: '500px',
        padding: '20px',
        fontFamily:
          '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      }}
    >
      {/* 标题栏 */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '16px',
          paddingBottom: '12px',
          borderBottom: '1px solid #eee',
        }}
      >
        <div>
          <h3
            style={{
              margin: 0,
              fontSize: '18px',
              color: '#333',
              fontWeight: 600,
            }}
          >
            🎯 批量操作
          </h3>
          <p
            style={{
              margin: '4px 0 0 0',
              fontSize: '14px',
              color: '#666',
            }}
          >
            已选中 {selectedCount} 个单元格
          </p>
        </div>
        <button
          onClick={onClose}
          style={{
            background: 'none',
            border: 'none',
            fontSize: '20px',
            cursor: 'pointer',
            color: '#999',
            width: '32px',
            height: '32px',
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
          onMouseEnter={e => {
            e.currentTarget.style.backgroundColor = '#f5f5f5';
          }}
          onMouseLeave={e => {
            e.currentTarget.style.backgroundColor = 'transparent';
          }}
        >
          ✕
        </button>
      </div>

      {/* 选择统计信息 */}
      <div
        style={{
          backgroundColor: '#f8f9fa',
          borderRadius: '8px',
          padding: '12px',
          marginBottom: '16px',
          fontSize: '13px',
          lineHeight: '1.5',
        }}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            marginBottom: '4px',
          }}
        >
          <span>📍 涉及房间数量:</span>
          <span style={{ fontWeight: 600, color: '#2196f3' }}>
            {stats.uniqueRooms} 个房间
          </span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span>📅 涉及日期数量:</span>
          <span style={{ fontWeight: 600, color: '#4caf50' }}>
            {stats.uniqueDates} 个日期
          </span>
        </div>
      </div>

      {/* 操作按钮网格 */}
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(2, 1fr)',
          gap: '8px',
          marginBottom: '16px',
        }}
      >
        {batchOperations.map(operation => {
          const statusConfig = RoomStatusManager.getStatusConfig(
            operation.targetStatus
          );

          return (
            <button
              key={operation.id}
              onClick={() => handleOperationClick(operation)}
              disabled={isProcessing}
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                padding: '12px 8px',
                backgroundColor: isProcessing ? '#f5f5f5' : 'white',
                border: `2px solid ${operation.color || statusConfig.color}`,
                borderRadius: '8px',
                cursor: isProcessing ? 'not-allowed' : 'pointer',
                transition: 'all 0.2s ease',
                fontSize: '13px',
                fontWeight: 500,
                opacity: isProcessing ? 0.6 : 1,
                minHeight: '80px',
                justifyContent: 'center',
              }}
              onMouseEnter={e => {
                if (!isProcessing) {
                  e.currentTarget.style.backgroundColor =
                    operation.color || statusConfig.color;
                  e.currentTarget.style.color = 'white';
                  e.currentTarget.style.transform = 'translateY(-2px)';
                  e.currentTarget.style.boxShadow =
                    '0 4px 12px rgba(0,0,0,0.15)';
                }
              }}
              onMouseLeave={e => {
                if (!isProcessing) {
                  e.currentTarget.style.backgroundColor = 'white';
                  e.currentTarget.style.color =
                    operation.color || statusConfig.color;
                  e.currentTarget.style.transform = 'translateY(0)';
                  e.currentTarget.style.boxShadow = 'none';
                }
              }}
            >
              <div style={{ fontSize: '20px', marginBottom: '4px' }}>
                {operation.icon}
              </div>
              <div style={{ textAlign: 'center', lineHeight: '1.2' }}>
                {operation.label}
              </div>
            </button>
          );
        })}
      </div>

      {/* 底部操作栏 */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          paddingTop: '12px',
          borderTop: '1px solid #eee',
        }}
      >
        <div style={{ fontSize: '12px', color: '#666' }}>
          💡 提示: 批量操作将同时更新所有选中的单元格
        </div>
        <div style={{ display: 'flex', gap: '8px' }}>
          <button
            onClick={onClose}
            style={{
              padding: '6px 16px',
              backgroundColor: '#6c757d',
              color: 'white',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer',
              fontSize: '13px',
              fontWeight: 500,
            }}
          >
            取消
          </button>
        </div>
      </div>

      {/* 处理中状态 */}
      {isProcessing && (
        <div
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(255,255,255,0.8)',
            borderRadius: '12px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexDirection: 'column',
            zIndex: 10,
          }}
        >
          <div
            style={{
              width: '32px',
              height: '32px',
              border: '3px solid #f3f3f3',
              borderTop: '3px solid #2196f3',
              borderRadius: '50%',
              animation: 'spin 1s linear infinite',
              marginBottom: '8px',
            }}
          />
          <div style={{ fontSize: '14px', color: '#666' }}>
            正在处理批量操作...
          </div>
        </div>
      )}

      <style>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
};

export default BatchOperationMenu;
